// index.js
var app = getApp();
var util = require('../../utils/util.js')
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: false,
    interval: 3000,
    duration: 1000,
    circular: true,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite: false,
    CurrentPid: 0,
    ReviewListLength: 0,
    animationData: "",
    showModalStatus: false,
    skuTitles: [],
    attrvalue: "",
    img: "",
    TotalCount: 0,
    showAppoint: false,
    typeList: [],
    disId: 0,
    agentId: 0,
    animationData2: "",
    showModalStatus2: false,
    productCode: "",
    pathGoods: "",
    showVideo: false,
    mallName: "",
    cardInfo: {},
    rankDiscount: 0,
    startDate: 0,
    showpost: false,
    productImageList: [],
    isAccredit: false,
    query: ''
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    util.recordActionTime(this.data.startDate, 22, this.data.CurrentPid)
  },

  onUnload: function () {
    util.recordActionTime(this.data.startDate, 22, this.data.CurrentPid)
  },


  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId")
    let uid = app.globalData.friendUid;
    if (app.globalData.userInfo) {
      uid = app.globalData.userInfo.Uid
    }
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/GetAiCard?uid=' + uid + '&staffId=' + cardId,
        success: function (res) {
          if (res.data.Code == 0) {
            that.setData({
              cardInfo: res.data.Data
            })
          }
        },
      })
    }
  },
  //进入聊天页面
  formSubmit: function (e) {
    var cardInfo = this.data.cardInfo.CardInfo;
    // var formId = e.detail.formId;
    // util.addFormIdMsg(formId);
    util.aiCardActionRecord(6);
    util.toChat(cardInfo);
    // wx.navigateTo({
    //   url: '/pages/weijieke/Business/Business?seltoid=' + cardInfo.Uid + '&name=' + cardInfo.Name
    // })
  },
  //是否授权登陆
  toShowToast: function () {
    let that = this;
    let back = '/pages/goods-details/index';
    wx.navigateTo({
      url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
    })
  },

  //会员折扣
  getUserInfoDiscount: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/User/GetUserInfo?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          var RankDiscount = res.data.Data.UserRankInfo.RankDiscount;
          if (RankDiscount) {
            that.setData({
              rankDiscount: (100 - parseFloat(RankDiscount)) / 10
            })
          }
        }
      }
    })
  },


  //获取商品二维码
  getWxaCode: function (path) {
    var that = this
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: path,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.data.productCode = 'https://static.711688.net.cn/upload/user/' + res.data.Data;
          }
        }
      },
    })
  },

  //获取评价列表
  pingjiaList: function (pid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/productreviewlist?pid=' + pid + '&page=1',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            ReviewListLength: res.data.Data.ProductReviewList.length,
            TotalCount: res.data.Data.PageModel.TotalCount
          })
        }
      }
    })
  },

  preview: function () {
    var that = this
    wx.previewImage({
      current: that.data.productCode, // 当前显示图片的http链接
      urls: [that.data.productCode] // 需要预览的图片http链接列表
    })
  },

  GetCouponTypeList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetSendingCouponTypeList',
      data: {
        storeid: app.globalData.storeId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var couPonList = res.data.Data
          for (var i = 0; i < couPonList.length; i++) {
            couPonList[i].UseStartTime = couPonList[i].UseStartTime.slice(0, 10)
            couPonList[i].UseEndTime = couPonList[i].UseEndTime.slice(0, 10)
          }
          that.setData({
            typeList: res.data.Data
          })
        }
      }
    })
  },
  //规格选择颜色变化
  selectAttr: function (e) {
    var that = this;
    var namearr = e.currentTarget.dataset.namearr
    var attrid = e.currentTarget.dataset.attrid
    var skulist = that.data.skuTitles
    var kid = 0//颜色变化初始值
    for (var i = 0; i < skulist.length; i++) {//一级数组
      var nameArr = skulist[i].nameArr
      for (var j = 0; j < nameArr.length; j++) {//二级数组
        if (nameArr[j].IsInput == 1) {
          var nameAttrValue = nameArr[j].InputValue
        } else {
          var nameAttrValue = nameArr[j].attrvalue
        }
        if (nameAttrValue == namearr) {
          if (nameArr[j].kid == 0) {
            nameArr[j].kid = 1
          }
          else {
            nameArr[j].kid = 0
          }
        }
        else if (nameAttrValue != namearr && attrid == nameArr[j].AttrId) {
          nameArr[j].kid = 0
        }
        else if (attrid != nameArr[j].AttrId) {
          if (nameArr[j].kid != 1) {
            nameArr[j].kid = 3
            that.selectionPid(skulist, namearr, attrid)
          }
        }
      }
    }
    that.setData({
      skuTitles: skulist
    })
    var pidArr = []
    for (var p = 0; p < skulist.length; p++) {//选中对应kid筛选pid
      var nameArry = skulist[p].nameArr
      var arry = skulist[p].arr
      for (var h = 0; h < nameArry.length; h++) {
        if (nameArry[h].kid == 1) {
          if (nameArry[h].IsInput == 0) {
            var nameAttrValue = nameArry[h].attrvalue
          } else {
            var nameAttrValue = nameArry[h].InputValue
          }
          for (var m = 0; m < arry.length; m++) {
            if (arry[m].IsInput == 0) {
              var arrAttrValue = arry[m].AttrValue
            } else {
              var arrAttrValue = arry[m].InputValue
            }
            if (nameAttrValue == arrAttrValue) {
              pidArr.push(arry[m].Pid)
            }
          }
        }
      }
    }
    var nary = pidArr.sort();
    that.arrRepeat(nary, skulist.length)//一共几组sku skulist.length
  },
  //查找数组重复次数的组合pid
  arrRepeat: function (arr, skuCount) {
    var that = this;
    let pid = 0;
    var arrStr = JSON.stringify(arr), str;
    for (var i = 0; i < arr.length; i++) {
      if ((arrStr.match(new RegExp(arr[i], "g")).length) == skuCount) {//出现重复的次数等于sku组的出现次数
        that.data.CurrentPid = arr[i]//最终的组合pid
        pid = arr[i]
      }
    }
    if (pid != 0) {
      that.getGoodsInfo()
    }
  },
  //返回选中的pid
  selectionPid: function (skulist, text, attrid) {
    var that = this;
    for (var i = 0; i < skulist.length; i++) {
      if (attrid == skulist[i].AttrId) {
        var arr = skulist[i].arr
        for (var j = 0; j < arr.length; j++) {
          if (arr[j].IsInput == 0) {
            var arrAttrValue = arr[j].AttrValue
          } else {
            var arrAttrValue = arr[j].InputValue
          }
          if (text == arrAttrValue) {
            var Pid = arr[j].Pid
            that.otherPid(skulist, Pid, attrid)
          }
        }
      }
    }
  },
  //判断另一组可选择的规格值
  otherPid: function (skulist, pid, attrid) {
    var that = this;
    var valueArr = []
    for (var i = 0; i < skulist.length; i++) {
      if (attrid != skulist[i].AttrId) {
        var arr = skulist[i].arr
        var nameArr = skulist[i].nameArr
        for (var j = 0; j < arr.length; j++) {
          if (pid == arr[j].Pid) {
            if (arr[j].IsInput == 0) {
              var AttrValue = arr[j].AttrValue
            } else {
              var AttrValue = arr[j].InputValue
            }
            that.check2(valueArr, AttrValue)
            if (!that.check2(valueArr, AttrValue)) {
              valueArr.push(AttrValue)
              for (var f = 0; f < valueArr.length; f++) {
                for (var k = 0; k < nameArr.length; k++) {
                  if (nameArr[k].IsInput == 0) {
                    var nameArrValue = nameArr[k].attrvalue
                  } else {
                    var nameArrValue = nameArr[k].InputValue
                  }
                  if (valueArr[f] == nameArrValue && nameArr[k].kid != 1) {
                    nameArr[k].kid = 0
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  //数组去重
  check2: function (arr, text) {
    var state = false;  //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i]) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  //接口取值
  onProductSKU: function (pid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/Product',
      data: {
        pid: pid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var skuList = res.data.Data.ProductSKUList
          var skuTitle = res.data.Data.CurrProductSkuList
          for (var k = 0; k < skuTitle.length; k++) {//初始化二维数组
            skuTitle[k].arr = []
            skuTitle[k].nameArr = []
          }
          that.ProductSKU(skuTitle, skuList);
        } else {
          wx.showModal({
            title: '获取失败',
            content: '',
            showCancel: false
          })
        }
      }
    })
  },
  //重新push新数组
  ProductSKU: function (skuTitle, skuList) {
    var that = this;
    var skuTitles = skuTitle
    var skuList = skuList
    for (var i = 0; i < skuTitles.length; i++) {
      for (var j = 0; j < skuList.length; j++) {
        if (skuTitles[i].AttrId == skuList[j].AttrId) {
          var f = {}
          f.AttrId = skuList[j].AttrId
          f.AttrName = skuList[j].AttrName
          f.AttrValue = skuList[j].AttrValue
          f.Pid = skuList[j].Pid
          f.RecordId = skuList[j].RecordId
          f.IsInput = skuList[j].IsInput
          f.InputValue = skuList[j].InputValue
          f.sid = 0
          f.ShowImg = app.globalData.image800_800host + skuList[j].ShowImg
          skuTitles[i].arr.push(f)
          if (skuList[j].IsInput == 1) {//手动输入
            var skuValue = skuList[j].InputValue
          } else {
            var skuValue = skuList[j].AttrValue
          }
          if (!that.check(skuTitles[i].nameArr, skuValue)) {
            skuTitles[i].nameArr.push({
              attrvalue: skuList[j].AttrValue, kid: 0, AttrId: skuList[j].AttrId, IsInput: skuList[j].IsInput, InputValue: skuList[j].InputValue
            })
          }
        }
      }
    }
    that.setData({
      skuTitles: skuTitles
    })
  },
  //数组去重
  check: function (arr, text) {
    var state = false;  //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i].attrvalue || text == arr[i].InputValue) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  // 底部弹出层
  showModal: function () {
    // 显示遮罩层
    this.onProductSKU(this.data.CurrentPid)
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    that.GetCouponTypeList()
    let currentPid = 0;
    let params = decodeURIComponent(e.scene);
    console.log('小程序码携带的参数', params);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let param = '';//参数
      let plist = '';
      if (params.indexOf('p-') != -1) {
        param = params.match(/p-(\S*)/)[1];//参数
        plist = param.toString().split('_');
      } else {
        param = params.match(/p=(\S*)/)[1];//参数
        plist = param.toString().split('#');
      }
      if (plist[0]) {
        wx.setStorageSync("disid", plist[0]);
      }
      if (plist[1]) {
        wx.setStorageSync("agentid", plist[1]);
      }
      currentPid = plist[2];
      if (plist[3]) {
        wx.setStorageSync("cardId", plist[3]);
      }
    } else {
      if (e.agentId) {
        wx.setStorageSync("agentid", e.agentId);
      }
      if (e.disId) {
        wx.setStorageSync("disid", e.disId);
      }
      currentPid = e.id;
      if (e.cardId) {
        wx.setStorageSync("cardId", e.cardId);
      }
    }
    that.data.CurrentPid = currentPid;
    if (e.isFriendState) {
      that.pingjiaList(currentPid)
      that.getGoodsInfo();
      that.GetSharePagePath();
      that.getAiCardInfo();
    }
  },
  // subscribe预约
  subscribe: function (e) {
    wx.navigateTo({
      url: '/pages/yuyue/index?pid=' + this.data.CurrentPid + "&name=" + this.data.goodsDetail.ProductInfo.Name,
    });
  },
  selectGoods: function (e) {
    wx.navigateTo({
      url: '/pages/pingjia-list/index?pid=' + this.data.CurrentPid
    })
  },
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function (e) {
    if (e.detail.value) {
      if (this.data.buyNumber < this.data.buyNumMax) {
        this.setData({
          buyNumber: e.detail.value
        })
      }
    } else {
      if (this.data.buyNumber < this.data.buyNumMax) {
        var currentNum = this.data.buyNumber;
        currentNum++;
        this.setData({
          buyNumber: currentNum
        })
      }
    }
  },
  addShopCar: function (e) {
    let that = this;
    let back = '/pages/goods-details/index';
    console.log(back);
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后方可购买商品，是否确认登陆？',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
            })
          }
        }
      })
      return;
    }
    if (e != 0) {
      var add = e.currentTarget.dataset.add
    }
    if (that.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: that.data.CurrentPid,
        buyCount: that.data.buyNumber
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data
          });
          if (add != 1) {
            that.goShopCar();
          } else {
            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
              duration: 2000
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  goShopCar: function () {
    let that = this;
    let back = '/pages/goods-details/index';
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后才能查看购物车，是否确认登陆',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
            })
          }
        }
      })
      return;
    } else {
      wx.navigateTo({
        url: "/pages/shop-cart/index"
      });
    }
  },
  tobuy: function (e) {
    let that = this;
    let back = '/pages/goods-details/index';
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后方可购买商品,是否确认登陆',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
            })
          }
        }
      })
      return;
    }
    var isSkuProduct = e.currentTarget.dataset.sku
    if (isSkuProduct > 0) {
      that.showModal()
    } else {
      if (that.data.buyNumber < 1) {
        wx.showModal({
          title: '提示',
          content: '暂时缺货哦~',
          showCancel: false
        })
        return;
      }
      that.addShopCar(0);
    }
  },
  favorite: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/user/ProductFavorite',
      data: {
        pid: pid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var oldF = that.data.favorite;
          if (oldF) {
            wx.showModal({
              title: '取消收藏成功',
              content: '',
              showCancel: false
            })
          } else {
            wx.showModal({
              title: '收藏成功',
              content: '',
              showCancel: false
            })
          }
          that.setData({ favorite: !oldF })
        }
      }
    })
  },

  //数据初始化
  initPage: function () {
    var that = this;
    var getLocationPromisified = util.wxPromisify(that.getShopCart)
    getLocationPromisified({

    }).then(that.checkFavorite())
      .then(that.getGoodsInfo())
      .catch(function (res) {
        console.error("failed" + res)
      })
  },

  //判断收藏
  checkFavorite: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/CheckProductFavorite',
      data: {
        pid: that.data.CurrentPid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var f = res.data.Data;
          that.setData({ favorite: f })
        }
      }
    })
  },

  //获取购物车数据
  getShopCart: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({ shopNum: res.data.Data.TotalCount })
        }

      }
    })
  },

  //获取商品信息
  getGoodsInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: that.data.CurrentPid
      },
      success: function (res) {
        wx.hideLoading();
        var p = res.data.Data;
        if (!p.ProductInfo || p.ProductInfo.State != 0) {
          wx.showModal({
            title: '商品已下架',
            content: '',
            showCancel: false
          })
          return;
        }
        if (p.ProductInfo.ShowImg) {
          p.ProductInfo.ShowImg = app.globalData.image800_800host + p.ProductInfo.ShowImg;
        }
        for (var i = 0; i < p.ProductImageList.length; i++) {
          p.ProductImageList[i].ShowImg = app.globalData.image800_800host + p.ProductImageList[i].ShowImg;
        }
        that.getImgInfoHeight(p.ProductImageList)//设置图片自适应比例
        if (p.ExtGiftList) {
          for (var i = 0; i < p.ExtGiftList.length; i++) {
            p.ExtGiftList[i].ShowImg = app.globalData.image190_190host + p.ExtGiftList[i].ShowImg;
          }
        }

        var selectSizeTemp = "";
        var pnames = "";
        if (p.CurrProductSkuList.length > 0) {
          for (var i = 0; i < p.CurrProductSkuList.length; i++) {
            pnames += p.CurrProductSkuList[i].AttrName + ":";
            var value = p.CurrProductSkuList[i].AttrValue;
            if (p.CurrProductSkuList[i].IsInput) {
              value = p.CurrProductSkuList[i].InputValue;
            }
            selectSizeTemp = selectSizeTemp + " " + value;
            pnames += value + " "
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: p.ProductInfo.ShopPrice,
          });
        }
        if (p.ProductInfo.VideoSrc != "") {
          that.setData({
            showVideo: false
          })
        }
        util.aiCardActionRecord(22, p.ProductInfo.Name);
        console.log(p)
        that.setData({
          goodsDetail: p,
          selectSizePrice: p.ProductInfo.ShopPrice,
          buyNumMax: p.StockNumber,
          buyNumber: (p.StockNumber > 0) ? 1 : 0
        });
        WxParse.wxParse('article', 'html', p.ProductInfo.Description, that, 5);
      }
    })
  },

  //设置图片自适应
  getImgInfoHeight: function (list) {
    var that = this;
    var heightArr = [];
    var f = 0;
    for (let h = 0; h < list.length; h++) {
      wx.getImageInfo({
        src: list[h].ShowImg,
        success: function (res) {
          list[h].width = res.width;
          list[h].height = res.height;
        },

        complete: function (res) {
          f++
          if (f == list.length) {
            console.log('执行完毕');
            for (let g = 0; g < list.length; g++) {
              //获取图片真实宽度  
              var imgwidth = list[g].width,
                imgheight = list[g].height,
                //宽高比  
                ratio = imgwidth / imgheight;
              //计算的高度值  
              var viewHeight = 750 / ratio;
              var vieheight = viewHeight
              heightArr.push(vieheight)
              list[g].imgheight = vieheight;
            }
            for (let t = 0; t < list.length; t++) {
              var maxN = that.checkMax(heightArr)
              list[t].maxHeight = maxN;
            }
            that.setData({ productImageList: list })
          } else {
            console.log("继续");
          }
        }
      })
    }
  },
  //判断最大值
  checkMax: function (heightArr) {
    var maxN = Math.max.apply(null, heightArr);
    return maxN;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.data.startDate = util.formatTime(new Date());
    // that.setData({ startDate: util.formatTime(new Date()) })
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      that.pingjiaList(that.data.CurrentPid)
      that.initPage();
      that.GetSharePagePath();
      that.getAiCardInfo();
      that.getUserInfoDiscount();
      util.isAccredit(function (isAccredit) {
        that.setData({
          isAccredit: isAccredit
        })
      });
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },


  //分享
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.ProductInfo.Name,
      path: this.data.pathGoods,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onShareTimeline: function (e) {
    let that = this;
    let query = that.data.query;
    if (!query) {
      query = 'id=' + that.data.CurrentPid + '&isFriendState=1'
    }
    return {
      title: that.data.goodsDetail.ProductInfo.Name,
      query: query,
      imageUrl: that.data.goodsDetail.ProductInfo.ShowImg
    }
  },

  //分销
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    let uid = app.globalData.friendUid;
    if (app.globalData.userInfo) {
      uid = app.globalData.userInfo.Uid;
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: uid,
        storeId: app.globalData.storeId,
        agentId: agentId,
        disId: disId,
      },
      success: function (res) {
        if (res.data.Code == 0) {
          let cardId = wx.getStorageSync('cardId');
          var path = '';
          let pathGoods = '';
          let disId = 0;
          let agentId = 0;
          let query = '';
          if (res.data.Data.IsAgent == 0) {
            disId = res.data.Data.Id;
            agentId = res.data.Data.AgentDId;
            // path = "/pages/goods-details/index?disId=" + res.data.Data.Id + "&agentId=0&id=" + that.data.CurrentPid
          } else {
            agentId = res.data.Data.Id;
            // path = "/pages/goods-details/index?disId=0&agentId=" + res.data.Data.Id + "&id=" + that.data.CurrentPid
          }
          path = "/pages/goods-details/index?p=" + disId + "#" + agentId + "#" + that.data.CurrentPid + "#" + cardId;
          pathGoods = "/pages/goods-details/index?disId=" + disId + "&agentId=" + agentId + "&id=" + that.data.CurrentPid + "&cardId=" + cardId;
          query = "disId=" + disId + '&agentId=' + agentId + '&id=' + that.data.CurrentPid + '&isFriendState=1&cardId=' + cardId;
          if (!that.data.productCode) {
            that.getWxaCode(path);
          }
          that.data.pathGoods = pathGoods;
          that.data.query = query;
        }
      }
    })
  },

  /**
   * 生成产品海报
   */

  //下载产品图片
  getAvaterInfo: function () {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    that.setData({ showpost: true })
    var goodsDetail = that.data.goodsDetail;
    var productImage = goodsDetail.ProductImageList[0].ShowImg;
    if (productImage) {
      wx.downloadFile({
        url: productImage,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var productSrc = res.tempFilePath;
            that.getQrCode(productSrc);
          } else {
            wx.showToast({
              title: '产品图片下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var productSrc = "";
                that.getQrCode(productSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var productSrc = "";
      that.getQrCode(productSrc);
    }
  },

  //下载二维码
  getQrCode: function (productSrc) {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    var productCode = that.data.productCode;
    if (productCode) {
      wx.downloadFile({
        url: productCode,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.sharePosteCanvas(productSrc, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.sharePosteCanvas(productSrc, codeSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var codeSrc = "";
      that.sharePosteCanvas(productSrc, codeSrc);
    }
  },

  //canvas绘制分享海报
  sharePosteCanvas: function (avaterSrc, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    var productInfo = that.data.goodsDetail.ProductInfo;
    const ctx = wx.createCanvasContext('myCanvas');
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width;
      var left = rect.left;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);

      //头像
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, 0, 0, width, width);
        ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }


      //产品名称
      if (productInfo.Name) {
        const CONTENT_ROW_LENGTH = 24; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = that.textByteLength((productInfo.Name).substr(0, 40), CONTENT_ROW_LENGTH);
        ctx.setTextAlign('left');
        ctx.setFillStyle('#000');
        ctx.setFontSize(14);
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          ctx.fillText(contentArray[m], 15, width + 35 + contentHh * m);
        }
      }


      //产品金额
      if (productInfo.ShopPrice || productInfo.ShopPrice == 0) {
        ctx.setFontSize(25);
        ctx.setFillStyle('#F57509');
        ctx.setTextAlign('left');
        ctx.fillText("¥" + productInfo.ShopPrice, left, width + 110); //电话
      }


      //  绘制二维码cardInfo.CardInfo.QrCode
      if (codeSrc) {
        ctx.drawImage(codeSrc, left + 185, width + 15, width / 4, width / 4)
        ctx.setFontSize(10);
        ctx.setFillStyle('#000');
        ctx.fillText("微信扫码或长按识别", left + 175, width + 110);
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closePoste();
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  closePoste: function () {
    this.setData({ showpost: false })
  }

})